#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#include "adc.h"

#define BAUD 500000
#define ACK 0xfa
#define BAUD_PRESCALE (((F_CPU / (BAUD * 16UL))) - 1)

void init_usart(void) {
    UCSRB |= (1 << RXEN) | (1 << TXEN) | (1 << RXCIE);
    UCSRC |= (1 << URSEL) | (0 << UCSZ2) | (1 << UCSZ1) | (1 << UCSZ0) | (1 << UPM1) | (1 << UPM0); //Odd Parity  8-bit
    UBRRL = BAUD_PRESCALE;//UBRRL_VALUE;
    UBRRH = (BAUD_PRESCALE >> 8);//UBRRH_VALUE;
}

void usart_send_byte(uint8_t byte){
    while((UCSRA & (1 << UDRE)) == 0);
    UDR = byte;
}


ISR(USART_RXC_vect) {
    //Packet size: 2bytes
    static uint8_t packt = 0;

    packt = UDR;
    switch(packt){
        case 0x00:
            usart_send_byte(ACK);
            break;
        case 0x01:
            start_timer();
            break;
        case 0x02:
            stop_timer();
            break;
        default:
            ADMUX = ((packt & 0xf0) >> 4) | (ADMUX & ~0x1f);
            break;
    }
}
